import { Modal, App } from 'antd';
import { useState } from 'react';
import { auditTask, updateImageStatus, fetchLastReviewValid } from 'apis/annotation/task';
import { AnnotationStatus, ApprovalData, JobStatusEnum } from 'typings/annotion/task';
import { useSelector, useDispatch } from 'react-redux';
import { CombinedState } from 'reducers';
import { getTaskImage } from 'actions/annotation-actions';
import { useNavigate } from 'react-router-dom-v5-compat';

// 1:待标注 2:待初审 3:初审驳回 4:待复审 5:复审驳回 6:复审通过 7:已关闭
// 审批状态
export type Status = AnnotationStatus;
// enum
export default function useTask() {
    const { message } = App.useApp();
    const [loading, setLoading] = useState(false);
    const [statusLoading, setStatusLoading] = useState(false);
    const approval = useSelector((state: CombinedState) => state.annotation.approval);
    const subTaskId = useSelector((state: CombinedState) => state.annotation.approval.subTaskId);
    const filename = useSelector((state: CombinedState) => state.annotation.player.frame.filename);
    const [imageData] = approval.taskImageInfo.subTaskImage?.filter((image) => image.imageName === filename) ?? [];
    const [rejectVisiable, setRejectVisible] = useState(false);
    const [rejectData, setRejectData] = useState({
        title: '初审驳回',
        status: 3 as AnnotationStatus,
    });

    const dispatch = useDispatch();
    const navigate = useNavigate();

    async function handleApproval(data: ApprovalData) {
        setLoading(true);
        try {
            await auditTask(data);
            message.success('操作成功');
            setTimeout(() => {
                navigate('/taskManager', { replace: true });
            });
            // todo 重新获取任务信息
            // dispatch(getTaskImage(subTaskId));
        } catch (error) {
            console.log(error);
        } finally {
            setLoading(false);
        }
    }

    async function handleChangeImageStatus() {
        setStatusLoading(true);
        try {
            await updateImageStatus({
                imageId: imageData.id,
                imageStatus: imageData.temStatus === 0 ? 1 : 0,
            });
            message.success('操作成功');
            // todo 重新获取任务信息
            dispatch(getTaskImage(subTaskId));
        } catch (error) {
            console.log(error);
        } finally {
            setStatusLoading(false);
        }
    }

    function handleReject(title: string, status: Status): void {
        setRejectData({
            title,
            status,
        });
        setRejectVisible(true);
    }

    async function handleRejectSubmit(values: any, loadinCallback?: () => void): Promise<void> {
        try {
            const { remark } = values;
            const data = {
                subTaskStatus: rejectData.status,
                subTaskId,
                remark,
            };
            await auditTask(data);
            message.success('操作成功');
            setTimeout(() => {
                navigate('/taskManager', { replace: true });
            });
            // todo 重新获取任务信息
            // dispatch(getTaskImage(subTaskId));
        } catch (error) {
            console.log(error);
        } finally {
            setRejectVisible(false);
            loadinCallback?.();
        }
    }

    function initModal(config: {
        type?: string;
        title: string;
        content: string | React.ReactNode;
        okText?: string;
        onOk?: Function;
        onCancel?: Function;
        cancelText?: string | React.ReactNode;
    }): void {
        const modal = config.type === 'confirm' ? Modal.confirm({}) : Modal.info({});
        modal.update({
            title: config.title,
            content: config.content,
            closable: false,
            okText: config.okText,
            onOk: () => {
                if (config.onOk) {
                    config.onOk();
                }
                modal.destroy();
            },
            onCancel: () => {
                if (config.onCancel) {
                    config.onCancel();
                }
                modal.destroy();
            },
            cancelText: config.cancelText || '取消',
        });
    }

    async function checkReview(jobId: number | string) {
        try {
            const res = await fetchLastReviewValid(jobId, subTaskId);
            if (res.valid) {
                initModal({
                    type: 'confirm',
                    title: '复审通过',
                    content: '请确认子任务是否复审通过？',
                    okText: '复审通过',
                    onOk: () => {
                        handleApproval({
                            subTaskStatus: JobStatusEnum.SECOND_REVIEW_APPROVED,
                            subTaskId,
                        });
                    },
                });
            } else {
                initModal({
                    type: 'confirm',
                    title: '提示',
                    content: '还有未完成复审的标签，请处理后再提交',
                    okText: '我知道了',
                    cancelText: '',
                });
            }
        } catch (error) {
            console.group(error);
        }
    }

    function handleSubmitReview() {
        initModal({
            type: 'confirm',
            title: '提交初审',
            content: '请确认是否将子任务提交初审？',
            okText: '提交初审',
            onOk: () => {
                handleApproval({
                    subTaskStatus: JobStatusEnum.WAITING_FIRST_REVIEW,
                    subTaskId,
                });
            },
        });
    }

    return {
        loading,
        statusLoading,
        subTaskId,
        approval,
        imageData,
        rejectVisiable,
        rejectData,
        handleApproval,
        handleChangeImageStatus,
        handleReject,
        handleRejectSubmit,
        setRejectVisible,
        checkReview,
        handleSubmitReview,
    };
}
